#!/usr/bin/perl -w
$|++;
use strict;
use Switch;
use File::Basename;
use HTTP::Daemon;
use HTTP::Status;
use IO::Socket::INET;
my $fifo_file = "/tmp/wm_binding.fifo";
my $ctxInput_fifo = '/tmp/contextInput';

#if($#ARGV == 0){
#  my $clientOrder = shift;
#  $clientOrder = "echo $clientOrder > $fifo_file";
#  print "$clientOrder\n";
#  system($clientOrder);
#  exit 0;
#}


my $fichier_conf = dirname(__FILE__) . "/compiz.bindings";
our $qmlDir = dirname(__FILE__) . "/../qml/contexts/";

print "conf_file  is :  $fichier_conf \n";
our %config;
reloadConf();  
our $state = 'empty';

#our $contexting


unless(-p $fifo_file){
    system('mknod', $fifo_file, 'p')
		  && die "can't mknod $fifo_file: $!";
}
unless(-p $ctxInput_fifo){
    system('mknod', $ctxInput_fifo, 'p')
		  && die "can't mknod $ctxInput_fifo: $!";
}

my $pidChild = fork();

if($pidChild == 0){
  #je suis le fils...
  my $fifo_fh;
  my $MENU_CTX;
  print "open CTX menu\n";
  my $cmd = "tail -f $ctxInput_fifo | simpleqmlplayer -name=remoteMenu -flags=WindowStaysOnTopHint,X11BypassWindowManagerHint";
  #my $cmd = "tail -f $ctxInput_fifo | simpleqmlplayer -flags=WindowStaysOnTopHint,FramelessWindowHint";
  
  print "exec<$cmd>\n";
  unless (fork) {
    # Si le processus est le fils,on le remplace par la commande demandée coe ça si problème les fils meurents
    exec ($cmd);
  }
  #open(MENU_CTX, "|$cmd ") || die "open simpleqmlplayer failed: $!\n";
  	  
  open($fifo_fh, "+< $fifo_file") or die "The FIFO file \"$fifo_file\" is missing, and this program can't run without it.";
  while(<$fifo_fh>){
    chomp;
    print "exec<$_>\n";
   if($_ eq '_reloadconf') {
      print "reloadConf \n";
      reloadConf();
      next;
   }elsif ($_ eq '_showctx') {
	print "showing ctx \n";
	my $pos = `xdotool getactivewindow getwindowgeometry | grep -o -e  [0-9]*,[0-9]*`;
	my $geo = `xdotool getactivewindow getwindowgeometry | grep -o -e  [0-9]*x[0-9]*`;
	my $win_name = `xdotool getactivewindow getwindowname | rev | cut -d" " -f 1 |rev`;
	chomp($pos);
	chomp($geo);
	chomp($win_name);
	
	print "pos<$pos>\n";
	print "geo<$geo>\n";
	print "win_name<$win_name>\n";
	my $qmlFileName = $qmlDir."$win_name.qml";
	if(! -e $qmlFileName){
	  $qmlFileName=$qmlDir."default.qml";
	}
	print "qmlFi****leName<$qmlFileName>\n";
	
	print "load params and show *************\n";
	#print MENU_CTX "onLoadPosAndSize=$pos=$geo\n";
	#print MENU_CTX "loadfile=$qmlFileName\n";
	#print MENU_CTX "setTitle=$win_name.control\n";
	#print MENU_CTX "show\n";
	system("echo onLoadPosAndSize=$pos=$geo > $ctxInput_fifo");
	print "onLoadPosAndSize sent===============!!\n";
	system("echo loadfile=$qmlFileName > $ctxInput_fifo");
	print "loadfile sent!!\n";
	system("echo setTitle=$win_name.control > $ctxInput_fifo");
	print "setTitle sent!!\n";
	system("echo show > $ctxInput_fifo");
	print "show sents!!\n";
	next;
    }
    workConfBindings($_);
    
  }
  close($fifo_fh);
  if($MENU_CTX){
    close($MENU_CTX);
  }
  exit 0;
  #fin du processus fils
}else{
  #je suis le père...
  my $client;
  my $d = HTTP::Daemon->new ( LocalPort => 8888
    #, Type => SOCK_STREAM
    , Reuse => 1
    , Listen => 5
    , Proto => 'tcp') or die "Probleme serveur";
  
  print "Please contact me on 8888 \n";
  while (my $client = $d->accept) {
    if (my $r = $client->get_request) {
	my $urlPath = $r->url->path;
	#print "request:*$urlPath*\n";
	my @cmd = split('/',$urlPath);
	shift(@cmd);
	my $c1 = shift(@cmd);
	if($c1 eq 'action'){
	  print "request:*$urlPath*\n";
	  my $c2 = shift(@cmd);
	  system("echo $c2 > $fifo_file");
	  print $client "-OK-\n";
	}elsif($c1 eq 'stop-server'){
	  print "stopping the server\n";
	  print $client "-OK-\n";
	  kill 9, $pidChild;
	  last;
	}else {
	  print $client "-UNKNOWN-\n";
	}
      }
  }

  exit 0;
  #fin du père
}


sub reloadConf {
 open CONFIG, "$fichier_conf" or die "Couldn't read config file $fichier_conf: $!\n";
  while (<CONFIG>) {
      next if (/^#|^\s*$/);  # skip blanks and comments
      chomp;
      my ($variable, $value) = split /=/;
      $config{$variable} = $value;
  }
  close CONFIG;
}


sub workConfBindings {
 $_ = shift;
 
 my $action;
 my $newState;
 print "state<$state>\n";
 if($state ne 'empty'){
    $action = $config{"$state.$_"};
    $newState = $config{"$state.$_.state"};
 }else{
    $action = $config{$_};
    $newState = $config{"$_.state"};
 }
 if(!$action){
    $action = $config{"ALL_STATE.$_"};
 }
 if($action && ($action ne 'empty') ){
  print "action<$action>\n";
  unless (fork) {
    # Si le processus est le fils,on le remplace par la commande demandée coe ça si problème les fils meurents
    exec ($action);
  }
 }
 
 if($newState){
  print "newState<$newState>\n";
  $state=$newState;
 }
 
}
















